import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { 
  Button, 
  List, 
  Radio, 
  Switch, 
  message, 
  Modal,
  Input,
  Form
} from 'antd';
import { 
  ArrowLeftOutlined, 
  EnvironmentOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { getAddresses, addAddress, getUserInfo } from '../../utils/storage';
import { orderAPI } from '../../services/api';
import { usePoints as usePointsUtil } from '../../utils/points';
import './OrderConfirm.css';
import { pad } from 'crypto-js';

const OrderConfirm = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [addresses, setAddresses] = useState([]);
  const [selectedAddress, setSelectedAddress] = useState(null);
  const [usePoints, setUsePoints] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState('alipay');
  const [showAddressModal, setShowAddressModal] = useState(false);
  const [form] = Form.useForm();
  
  const products = location.state?.products || [];
  const fromBuyNow = location.state?.fromBuyNow || false;
  const userInfo = getUserInfo();

  useEffect(() => {
    loadAddresses();
  }, []);

  const loadAddresses = () => {
    const userAddresses = getAddresses();
    setAddresses(userAddresses);
    if (userAddresses.length > 0) {
      const defaultAddress = userAddresses.find(addr => addr.isDefault) || userAddresses[0];
      setSelectedAddress(defaultAddress);
    }
  };

  const calculateTotal = () => {
    return products.reduce((total, item) => total + item.price * item.quantity, 0);
  };

  const calculateDiscount = () => {
    if (!usePoints || !userInfo?.points) return 0;
    const total = calculateTotal();
    const maxDiscount = Math.min(userInfo.points * 0.01, total * 0.1); // 积分抵扣，最多抵扣10%
    return Math.floor(maxDiscount * 100) / 100;
  };

  const getFinalTotal = () => {
    return calculateTotal() - calculateDiscount();
  };

  const handleAddAddress = async (values) => {
    try {
      const newAddress = {
        ...values,
        isDefault: addresses.length === 0
      };
      addAddress(newAddress);
      loadAddresses();
      setShowAddressModal(false);
      form.resetFields();
      message.success('地址添加成功');
    } catch (error) {
      message.error('添加地址失败');
    }
  };

  const handleSubmitOrder = async () => {
    if (!selectedAddress) {
      console.log('selectedAddress: ', selectedAddress); 
      message.error('请选择收货地址');
      return;
    }

    if (products.length === 0) {
      console.log('products: ', products);
      message.error('购物车为空');
      return;
    }

    try {
      const orderData = {
        products,
        address: selectedAddress,
        paymentMethod,
        usePoints,
        pointsDiscount: calculateDiscount(),
        totalAmount: getFinalTotal(),
        originalAmount: calculateTotal()
      };

      const response = await orderAPI.createOrder(orderData);
      console.log('response: ', response);
      if (response.success) {
        // 跳转到支付页面
        navigate('/app/payment', { 
          state: { 
            orderId: response.data.id,
            orderData: {
              ...orderData,
              orderNo: response.data.orderNo,
              fromCart: !fromBuyNow, // 标记是否来自购物车
              paymentMethod: paymentMethod // 传递选择的支付方式
            }
          } 
        });
      }
    } catch (error) {
      message.error('创建订单失败');
    }
  };

  return (
    <div className="order-confirm">
      {/* 头部导航 */}
      <div className="order-header">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
        />
        <span className="header-title">确认订单</span>
      </div>

      {/* 收货地址 */}
      <div className="address-section">
        {selectedAddress ? (
          <div 
            className="address-item selected"
            onClick={() => navigate('/app/address')}
          >
            <div className="address-icon">
              <EnvironmentOutlined />
            </div>
            <div className="address-info">
              <div className="address-header">
                <span className="receiver-name">{selectedAddress.name}</span>
                <span className="receiver-phone">{selectedAddress.phone}</span>
              </div>
              <div className="address-detail">
                {selectedAddress.province} {selectedAddress.city} {selectedAddress.district} {selectedAddress.detail}
              </div>
            </div>
            <div className="address-arrow">
              <span style={{ color: '#000', fontSize: '12px', fontWeight: 'bold' }}>点击更换地址</span>
            </div>
          </div>
        ) : (
          <div 
            className="add-address-btn"
            onClick={() => setShowAddressModal(true)}
          >
            <PlusOutlined /> 添加收货地址
          </div>
        )}
      </div>

      {/* 商品列表 */}
      <div className="order-products">
        <div className="section-title">商品信息</div>
        {products.map(item => (
          <div key={item.cartId || item.id} className="order-product-item">
            <img src={item.images[0]} alt={item.name} className="product-image" />
            <div className="product-info">
              <div className="product-name">{item.name}</div>
              {item.selectedSpecs && (
                <div className="product-specs">
                  {Object.entries(item.selectedSpecs).map(([key, value]) => (
                    <span key={key}>{key}: {value} </span>
                  ))}
                </div>
              )}
              <div className="product-price-qty">
                <span className="price">¥{item.price}</span>
                <span className="quantity">x{item.quantity}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 积分抵扣 */}
      {userInfo?.points > 0 && (
        <div className="points-section">
          <div className="points-item">
            <span>使用积分抵扣</span>
            <div className="points-control">
              <span className="points-info">
                可用积分: {userInfo.points} (最高可抵扣¥{Math.floor(userInfo.points * 0.01 * 100) / 100})
              </span>
              <Switch 
                checked={usePoints}
                onChange={setUsePoints}
              />
            </div>
          </div>
          {usePoints && (
            <div className="discount-info">
              积分抵扣: -¥{calculateDiscount()}
            </div>
          )}
        </div>
      )}

      {/* 支付方式 */}
      <div className="payment-section">
        <div className="section-title">支付方式</div>
        <Radio.Group 
          value={paymentMethod} 
          onChange={(e) => setPaymentMethod(e.target.value)}
          className="payment-methods"
        >
          <Radio value="alipay" className="payment-option">
            <div className="payment-item">
              <span className="payment-icon" style={{background: "url('https://cdn4.iconfinder.com/data/icons/logos-and-brands/512/13_Alipay_logo_logos-1024.png') no-repeat center center", backgroundSize: 'contain', width: '26px', height: '26px', marginLeft: '5px'}}></span>
              <span>支付宝</span>
            </div>
          </Radio>
          <Radio value="wechat" className="payment-option">
            <div className="payment-item">
              <span className="payment-icon" style={{background: "url('https://cdn3.iconfinder.com/data/icons/social-messaging-ui-color-shapes-2-free/128/social-wechat-circle-512.png') no-repeat center center", backgroundSize: 'contain', width: '26px', height: '26px', marginLeft: '5px'}}></span>
              <span>微信支付</span>
            </div>
          </Radio>
          <Radio value="bankcard" className="payment-option">
            <div className="payment-item">
              <span className="payment-icon" style={{background: "url('https://cdn1.iconfinder.com/data/icons/business-547/50/81-512.png') no-repeat center center", backgroundSize: 'contain', width: '26px', height: '26px', marginLeft: '5px'}}></span>
              <span>银联支付</span>
            </div>
          </Radio>
        </Radio.Group>
      </div>

      {/* 订单金额 */}
      <div className="order-summary">
        <div className="summary-item">
          <span>商品总额</span>
          <span>¥{calculateTotal().toFixed(2)}</span>
        </div>
        <div className="summary-item">
          <span>运费</span>
          <span>免运费</span>
        </div>
        {usePoints && calculateDiscount() > 0 && (
          <div className="summary-item discount">
            <span>积分抵扣</span>
            <span>-¥{calculateDiscount().toFixed(2)}</span>
          </div>
        )}
        <div className="summary-total">
          <span>实付款</span>
          <span className="total-amount">¥{getFinalTotal().toFixed(2)}</span>
        </div>
      </div>

      {/* 底部提交按钮 */}
      <div className="order-submit">
        <div className="submit-info">
          <div className="total-text">
            合计: <span className="total-price">¥{getFinalTotal().toFixed(2)}</span>
          </div>
        </div>
        <Button 
          type="primary"
          size="large"
          onClick={handleSubmitOrder}
          className="submit-btn"
        >
          提交订单
        </Button>
      </div>

      {/* 添加地址弹窗 */}
      <Modal
        title="添加收货地址"
        open={showAddressModal}
        onCancel={() => setShowAddressModal(false)}
        footer={null}
        className="address-modal"
        width={300}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAddAddress}
        >
          <Form.Item
            name="name"
            label="收货人"
            rules={[{ required: true, message: '请输入收货人姓名' }]}
          >
            <Input placeholder="请输入收货人姓名" />
          </Form.Item>
          
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          
          <Form.Item
            name="province"
            label="省份"
            rules={[{ required: true, message: '请输入省份' }]}
          >
            <Input placeholder="请输入省份" />
          </Form.Item>
          
          <Form.Item
            name="city"
            label="城市"
            rules={[{ required: true, message: '请输入城市' }]}
          >
            <Input placeholder="请输入城市" />
          </Form.Item>
          
          <Form.Item
            name="district"
            label="区县"
            rules={[{ required: true, message: '请输入区县' }]}
          >
            <Input placeholder="请输入区县" />
          </Form.Item>
          
          <Form.Item
            name="detail"
            label="详细地址"
            rules={[{ required: true, message: '请输入详细地址' }]}
          >
            <Input.TextArea placeholder="请输入详细地址" rows={3} />
          </Form.Item>
          
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              保存地址
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default OrderConfirm; 